//
//  HTRegisterSecondStepVC.m
//  TruckUser
//
//  Created by Ting Han on 2017/10/17.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTRegisterSecondStepVC.h"
#import "UIView+Layout.h"
#import "HTMineViewController.h"
#import "UIImageView+WebCache.h"
#import "HTImageClipViewController.h"

#import "HTPlaceView.h"

static NSString *const linces = @"linces";
static NSString *const photos = @"photos";
@interface HTRegisterSecondStepVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,HTPlaceViewDelegate,UITextFieldDelegate,HTImageClipViewControllerDelegate>
//头部
@property (weak, nonatomic) IBOutlet UILabel *driverLabel;
@property (weak, nonatomic) IBOutlet UILabel *truckLabel;
@property (weak, nonatomic) IBOutlet UIView *firstView;
@property (weak, nonatomic) IBOutlet UILabel *firstLabel;
@property (weak, nonatomic) IBOutlet UIView *secondView;
@property (weak, nonatomic) IBOutlet UILabel *secondLabel;
@property (weak, nonatomic) IBOutlet UIView *lineView;

@property (weak, nonatomic) IBOutlet UITextField *nameLabel;
@property (weak, nonatomic) IBOutlet UIView *tapYes;
@property (weak, nonatomic) IBOutlet UIImageView *yesImageView;
@property (weak, nonatomic) IBOutlet UIView *tapNo;

@property (weak, nonatomic) IBOutlet UIImageView *noImageView;
@property (weak, nonatomic) IBOutlet UIImageView *licenseImageView;
@property (weak, nonatomic) IBOutlet UITextField *licenseTextField;
@property (weak, nonatomic) IBOutlet UIView *licenseView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *middleHeight;
@property (weak, nonatomic) IBOutlet UILabel *placeLabel;
@property (weak, nonatomic) IBOutlet UITextField *detialAddressTextField;
@property (weak, nonatomic) IBOutlet UIImageView *storeImageView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollHeight;
@property (weak, nonatomic) IBOutlet UIButton *conformButton;

@property (nonatomic,assign) BOOL selectedYes;
@property (weak, nonatomic) IBOutlet UILabel *firstHiddenLabel;
@property (weak, nonatomic) IBOutlet UILabel *secondHiddenLabel;

@property (nonatomic,copy) NSString *licenseUrl;
@property (nonatomic,copy) NSString *photosUrl;

@property (weak, nonatomic) IBOutlet UIView *tapPlace;
@property (nonatomic,strong) HTPlaceView *placeView;
@property (nonatomic,copy) NSString *license;
@property (nonatomic,copy) NSString *licenseNumber;
@property (nonatomic,copy) NSString *placeString;

@end

@implementation HTRegisterSecondStepVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //未通过，通过
    if (self.isRegister == 3 || self.isRegister == 2) {
        [self netLoadDetialUserInfo];
        if (self.isRegister == 3) {
            [self setupImageViewPicture];
        }else{
            self.licenseTextField.userInteractionEnabled = NO;
         self.detialAddressTextField.userInteractionEnabled = NO;
            self.nameLabel.userInteractionEnabled = NO;
        }
    }else{//未认证
        [self setupImageViewPicture];
    }
    [self setupView];
}

- (void)didTapGesture:(UITapGestureRecognizer *)sender{
    if (sender.view.tag == 131) {
        if (self.selectedYes) {
            return;
        }
        self.selectedYes = YES;
        [self selectFirst];
    }else{
        if (!self.selectedYes) {
            return;
        }
        self.selectedYes = NO;
        [self selectSecond];
    }
}

- (void)setupView{
    [self setupHeadView];
    [self setupLicense];
    if (self.isRegister != 2) {
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
        self.tapYes.tag = 131;
        [self.tapYes addGestureRecognizer:tap1];
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
        self.tapNo.tag = 132;
        [self.tapNo addGestureRecognizer:tap2];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapPlace)];
        [self.tapPlace addGestureRecognizer:tap];
    }
    self.nameLabel.delegate = self;
    self.licenseTextField.delegate  = self;
    self.detialAddressTextField.delegate = self;

}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.nameLabel resignFirstResponder];
    [self.licenseTextField resignFirstResponder];
    [self.detialAddressTextField resignFirstResponder];
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)setupHeight{
    if (self.conformButton.bottom + 50 < kHTScreenHeight - kHTToolBarHeight - kHTNavicationBarAndStatusBar) {
        self.scrollHeight.constant = kHTScreenHeight;
    }else{
        self.scrollHeight.constant = self.conformButton.bottom + 50;
    }
}
#pragma mark --- headView & 营业执照
- (void)setupHeadView{
    self.title = @"公司信息";
    self.firstView.layer.masksToBounds = YES;
    self.firstView.layer.cornerRadius = self.firstView.frame.size.width/2;
    self.firstView.layer.borderWidth = 2;
    self.secondView.layer.masksToBounds = YES;
    self.secondView.layer.cornerRadius = self.secondView.frame.size.width/2;
    self.secondView.layer.borderWidth = 2;
    [self setType1Color:kBlueColor];
    [self setType2Color:kBlueColor];
}
- (void)setType1Color:(UIColor *)color{
    self.driverLabel.textColor = color;
    self.firstView.layer.borderColor = color.CGColor;
    self.firstLabel.textColor = color;
}
- (void)setType2Color:(UIColor *)color{
    self.truckLabel.textColor = color;
    self.secondView.layer.borderColor = color.CGColor;
    self.secondLabel.textColor = color;
    self.lineView.backgroundColor = color;
}

- (void)setupLicense{
    self.tapYes.backgroundColor = [UIColor whiteColor];
    self.tapYes.layer.masksToBounds = YES;
    self.tapYes.layer.borderColor = kBlueColor.CGColor;
    self.tapYes.layer.borderWidth = 1;
    self.tapNo.backgroundColor = [UIColor whiteColor];
    self.tapNo.layer.masksToBounds = YES;
    self.tapNo.layer.borderColor = kBlueColor.CGColor;
    self.tapNo.layer.borderWidth = 1;
    self.selectedYes = YES;
    [self selectFirst];
}
-(void)selectFirst{
    self.yesImageView.hidden = NO;
    self.noImageView.hidden = YES;
    self.licenseImageView.hidden = NO;
    self.licenseView.hidden = NO;
    self.firstHiddenLabel.hidden = NO;
    self.middleHeight.constant = 185;
    [self.view layoutIfNeeded];
    [self setupHeight];
}
- (void)selectSecond{
    self.yesImageView.hidden = YES;
    self.noImageView.hidden = NO;
    self.licenseImageView.hidden = YES;
    self.firstHiddenLabel.hidden = YES;
    self.licenseView.hidden = YES;
    self.middleHeight.constant = 1;
    [self.view layoutIfNeeded];
    [self setupHeight];
}

- (void)setupImageViewPicture{
    self.licenseTextField.userInteractionEnabled = YES;
    self.detialAddressTextField.userInteractionEnabled = YES;
    self.nameLabel.userInteractionEnabled = YES;
    self.licenseImageView.userInteractionEnabled = YES;
    self.storeImageView.userInteractionEnabled = YES;
    self.licenseImageView.tag = 194;
    self.storeImageView.tag = 195;
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didCallImage:)];
    [self.licenseImageView addGestureRecognizer:tap1];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didCallImage:)];
    [self.storeImageView addGestureRecognizer:tap2];
}
- (void)setupPlaceView{
    if (!self.placeView) {
        self.placeView = [[HTPlaceView alloc]initWithFrame:CGRectMake(0, 0, kHTScreenWidth, kHTScreenHeight - kHTNavicationBarAndStatusBar)];
        self.placeView.delegate = self;
        __weak typeof (self)weakSelf = self;
        self.placeView.blockCallBack = ^{
            [weakSelf removePlaceView];
        };
        self.placeView.placeViewType = HTPlaceViewTypeOther;
        [self.view addSubview:self.placeView];
    }
}
- (void)removePlaceView{
    if (self.placeView) {
        [self.placeView removeFromSuperview];
        self.placeView = nil;
    }
}
- (void)didTapPlace{
    [self setupPlaceView];
    
}
- (void)didChoiceItemWithModel:(HTAreaModel *)areaModel index:(NSInteger)index PlaceViewType:(HTPlaceViewType)placeType{
    if ( !(areaModel.areaType == HTAreaTypeArea || areaModel.areaType == HTAreaTypeNo)) {
        return;
    }
        NSString *total = @"";
    if ( areaModel.areaType == HTAreaTypeArea) {
        total = areaModel.title;
    }else if(areaModel.areaType == HTAreaTypeNo){
        
    }
    if (!(self.placeView.cityString == nil || self.placeView.cityString.length <= 0)) {
        total = [NSString stringWithFormat:@"%@%@",self.placeView.cityString,total];
    }
    if (!(self.placeView.provinceString == nil || self.placeView.provinceString.length <= 0)) {
        total = [NSString stringWithFormat:@"%@%@",self.placeView.provinceString,total];
    }
    if (total == nil || total.length <= 0) {
         total = areaModel.title;
    }
    self.placeLabel.text = total;
    self.placeLabel.textColor = [UIColor blackColor];
    self.placeString = total;
    [self removePlaceView];
}
#pragma mark --- 图片处理

- (void)didCallImage:(UITapGestureRecognizer *)sender{
    if (sender.view.tag == 194) {
        [self callActionSheetWithMessage:@"请您上传公司的营业执照" tag:sender.view.tag];
    }else if (sender.view.tag == 195){
        [self callActionSheetWithMessage:@"请你上传公司的门店照" tag:sender.view.tag];
    }
}
- (void)CropImageViewControllerWithImage:(UIImage*)portraitImg Frame:(CGRect )rect WithIndex:(NSInteger )index withPicker:(UIImagePickerController *)picker {
    HTImageClipViewController *imgCropperVC = [[HTImageClipViewController alloc] initWithImage:portraitImg cropFrame:rect limitScaleRatio:3.0];
    imgCropperVC.delegate = self;
    imgCropperVC.tag = index;
    [picker pushViewController:imgCropperVC animated:NO];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if(picker.view.tag == 194){
        [self CropImageViewControllerWithImage:portraitImg Frame:CGRectMake(0, kWidth(90), kHTScreenWidth, kHTScreenWidth/4*3) WithIndex:picker.view.tag withPicker:picker];
    }else if (picker.view.tag == 195){
        [self CropImageViewControllerWithImage:portraitImg Frame:CGRectMake(0, kWidth(90), kHTScreenWidth, kHTScreenWidth/4*3) WithIndex:picker.view.tag withPicker:picker];
    }

}
- (void)imageCropper:(HTImageClipViewController *)clipViewController didFinished:(UIImage *)editedImage{
    switch (clipViewController.tag) {
        case 194:
        {
            self.licenseImageView.image = editedImage;
            self.firstHiddenLabel.hidden = YES;
            [self netUpLoadPictureType:linces image:editedImage];
            [clipViewController dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        case 195:
        {
            self.storeImageView.image = editedImage;
            self.secondHiddenLabel.hidden = YES;
            [self netUpLoadPictureType:photos image:editedImage];
            [clipViewController dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}
- (void)imageCropperDidCancel:(HTImageClipViewController *)clipViewController{
    [clipViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)callActionSheetWithMessage:(NSString *)message tag:(NSInteger)tag{
    [UIAlertController actionSheetStyleShowInController:self title:@"温馨提示" message:message alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
        
        [alertActions addObject:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            PickerImage.view.tag = tag;
            PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            PickerImage.allowsEditing = NO;
            PickerImage.delegate = self;
            [self presentViewController:PickerImage animated:YES completion:nil];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"本地相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            PickerImage.view.tag = tag;
            PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            PickerImage.allowsEditing = NO;
            PickerImage.delegate = self;
            [self presentViewController:PickerImage animated:YES completion:nil];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    } completion:^{
        
    }];
}
#pragma mark --- 网络请求
- (void)netUpLoadPictureType:(NSString *)type image:(UIImage *)image{
    [self startHud];
    [HTHttpRequestManager requestUploadPictureWithType:type image:image success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"上传图片：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"图片保存失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        if ([type isEqualToString:linces]) {
            self.licenseUrl = responseObject[@"data"];
        }
        if ([type isEqualToString:photos]) {
            self.photosUrl = responseObject[@"data"];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"图片保存失败"];
    }];
}
- (IBAction)didClickConform:(UIButton *)sender {
    if (self.nameLabel.text == nil || self.nameLabel.text.length <= 0) {
        [HTShowUtil showMessage:@"请填写公司名称"];
        return;
    }
    if (self.selectedYes) {
        if (self.licenseTextField.text == nil || self.licenseTextField.text.length <= 0) {
            [HTShowUtil showMessage:@"请填写信用代码/注册码"];
            return;
        }
        self.licenseNumber = self.licenseTextField.text;
    }
    if (self.placeString == nil || self.placeString.length <= 0) {
        [HTShowUtil showMessage:@"请选择所在地"];
        return;
    }
    if (self.detialAddressTextField.text == nil || self.detialAddressTextField.text.length <= 0) {
        [HTShowUtil showMessage:@"请填写详细地址"];
        return;
    }
    if (self.selectedYes &&  (self.licenseUrl == nil || self.licenseUrl.length <= 0)) {
        [HTShowUtil showMessage:@"请上传营业执照照片"];
        return;
    }
    if (self.photosUrl == nil || self.photosUrl.length <= 0) {
        [HTShowUtil showMessage:@"请上传门店照"];
        return;
    }
    [self netLoadRegister];
}
- (void)netLoadRegister{
    [self startHud];
    [HTHttpRequestManager requestUserRegisterWithName:self.nameString carid:self.idcardString companyname:self.nameLabel.text addres:self.placeString addressinfor:self.detialAddressTextField.text licence:self.license licenceno:self.licenseNumber success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"认证---：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"认证失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
      //  [HTShowUtil showMessage:responseObject[@"message"]];
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[HTMineViewController class]]) {
                HTMineViewController *A =(HTMineViewController *)controller;
                [self.navigationController popToViewController:A animated:YES];
            }
        }
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
    }];
}
- (NSString *)license{
    if (self.selectedYes) {
        return @"1";
    }else{
        return @"0";
    }
}
- (NSString *)licenseNumber{
    if (self.selectedYes) {
        if (self.licenseTextField.text == nil || self.licenseTextField.text.length <= 0) {
            return @"";
        }
        return _licenseNumber;
    }else{
        return @"";
    }
}


- (void)netLoadDetialUserInfo{
    [self startHud];
    [HTHttpRequestManager requestUserInfoDetialsuccess:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"详情用户信息：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"用户信息获取失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        self.mineDetialModel = [HTMineDetialModel mj_objectWithKeyValues:responseObject[@"data"]];
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"用户信息获取失败"];
    }];
}
- (void)setMineDetialModel:(HTMineDetialModel *)mineDetialModel{
    _mineDetialModel = mineDetialModel;
    self.nameLabel.text = mineDetialModel.companyname;
    self.placeLabel.text = mineDetialModel.addres;
    self.detialAddressTextField.text = mineDetialModel.addressinfor;
    [self.storeImageView sd_setImageWithURL:[NSURL URLWithString:mineDetialModel.shops]];
    self.secondHiddenLabel.hidden = YES;
    if ([mineDetialModel.licence isEqualToString:@"0"]) {//没有营业执照
        self.selectedYes = NO;
        [self selectSecond];
    }else{//有营业执照
        [self.licenseImageView sd_setImageWithURL:[NSURL URLWithString:mineDetialModel.linces]];
        self.firstHiddenLabel.hidden = YES;
        self.licenseTextField.text = mineDetialModel.licenceno;
    }
    self.placeString = mineDetialModel.addres;
    self.photosUrl = mineDetialModel.shops;
    self.licenseUrl = mineDetialModel.linces;
    if (self.isRegister == 2) {
        self.conformButton.hidden = YES;
    }else{
         self.conformButton.hidden = NO;
    }
}
@end
